package com.huangdebiao.oa.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class DaoFactory<T> {

    /**
     * 创建sqlSession实例
     * @param transactionFlag 是否自动开启事务
     * @return
     */
    public static SqlSession getSession(boolean transactionFlag){

        String resource = "huangdebiao-mybatis.xml";
        Reader reader;
        SqlSession sqlSession;
        try {
            reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            sqlSession = sessionFactory.openSession(transactionFlag);
            return sqlSession;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建并返回session实例，不会自动提交
     * @param cls
     * @return
     */
    public T getDao(Class<T> cls){
        SqlSession session = getSession(false);
        return session.getMapper(cls);
    }

    /**
     * 创建并返回session实例，会自动提交
     * @param cls
     * @return
     */
    public T getDaoTransaction(Class<T> cls){
        SqlSession session = getSession(true);
        return session.getMapper(cls);
    }


}
